import React, {useState, useRef} from 'react';
import {Button, Space, Spin, Alert} from 'antd';
import {ReloadOutlined, ExportOutlined} from '@ant-design/icons';

const DbLog: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [iframeKey, setIframeKey] = useState(0);

  // 刷新iframe
  const handleRefresh = () => {
    setLoading(true);
    setError(null);
    setIframeKey(prev => prev + 1);
  };

  // 在新窗口打开
  const handleOpenNewWindow = () => {
    window.open('/api/druid/index.html', '_blank', 'noopener,noreferrer');
  };

  // iframe加载完成
  const handleIframeLoad = () => {
    setLoading(false);
    setError(null);

    // 检查iframe内容是否加载成功
    try {
      if (iframeRef.current && !iframeRef.current.contentWindow?.location.href.includes('/api/druid')) {
        setError('加载Druid监控失败，请检查权限或网络连接');
      }
    } catch (e) {
      // 跨域错误捕获
      setError('无法访问Druid监控，可能存在跨域限制');
    }
  };

  // iframe加载错误
  const handleIframeError = () => {
    setLoading(false);
    setError('加载Druid监控失败，请检查网络连接或服务状态');
  };

  return (
    <div style={{display: 'flex', flexDirection: 'column', height: '100%'}}>
      <div style={{marginBottom: 16}}>
        <Space>
          <Button
            type="primary"
            icon={<ReloadOutlined/>}
            onClick={handleRefresh}
            loading={loading}
          >
            刷新监控
          </Button>
          <Button
            icon={<ExportOutlined/>}
            onClick={handleOpenNewWindow}
          >
            在新窗口打开
          </Button>
        </Space>
      </div>

      {error && (
        <Alert
          message={error}
          type="error"
          showIcon
          style={{marginBottom: 16}}
        />
      )}

      <div style={{flex: 1, position: 'relative'}}>
        {loading && (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: 'rgba(255, 255, 255, 0.7)',
            zIndex: 10
          }}>
            <Spin size="large" tip="Druid监控加载中..."/>
          </div>
        )}

        <iframe
          key={iframeKey}
          ref={iframeRef}
          src="/api/druid/index.html"
          style={{
            width: '100%',
            height: '800px',
            border: 'none',
            visibility: loading ? 'hidden' : 'visible'
          }}
          title="Druid监控"
          sandbox="allow-same-origin allow-forms allow-scripts allow-top-navigation"
          onLoad={handleIframeLoad}
          onError={handleIframeError}
        />
      </div>
    </div>
  );
};

export default DbLog;
